
//

#import "CustomerNetworking.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import <CommonCrypto/CommonCrypto.h>
#import "AFNetworkActivityIndicatorManager.h"
#import "Reachability.h"
@implementation CustomerNetworking
+(void)customerConnectWithURL:(NSString *)url andParameters:(NSDictionary *)parameters andBlock:(ConnectionBlock)block
{
    
    CustomerNetworking *customer = [[CustomerNetworking alloc]init];
    [customer connectWithURL:url andParameters:parameters andBlock:block];
    
}




- (void)connectWithURL:(NSString *)url andParameters:(NSDictionary *)parameters andBlock:(ConnectionBlock)block
{
    //获取完整存储路径名字 (网址作为这个文件名)
    NSString *path = [CustomerNetworking getPathWithURL:url];
    
    //判断有没有网络
    NSInteger statusNum = [[self class] getNetWorkStatus];
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    //开始网络请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    manager.securityPolicy.allowInvalidCertificates = YES;
//通过判断parameters是否为空,确定使用POST orGET
//如果parameters为空,即为GET请求,如果不为空,则为POST请求
    
    if (parameters == nil) {
        
        if (statusNum > 0)
        {//GET请求
            [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                [netWorkManager stopMonitoring];
                block(responseObject);
                [responseObject writeToFile:path atomically:YES];
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
                NSLog(@"%@",error);
            }];
        } else {//无网络
          //管理
            NSFileManager *fileMan = [NSFileManager defaultManager];
            //先判断这个文件在不在
            if ([fileMan fileExistsAtPath:path]) {
                
                NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
                NSArray *arr = [NSArray arrayWithContentsOfFile:path];
                //加保护
                if (dic != nil) {
                    
                    block(dic);
                    
                }
                else if (arr != nil) {
                    
                    block(arr);
                }
            }
        }

    } else {
        
        if (statusNum > 0)
        {
            [manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                block(responseObject);
                [responseObject writeToFile:path atomically:YES];
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
                NSLog(@"%@",error);
                
            }];
        } else {
            
            NSFileManager *fileMan = [NSFileManager defaultManager];
            //先判断这个文件存不存在
            if ([fileMan fileExistsAtPath:path]) {
                NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
                NSArray *arr = [NSArray arrayWithContentsOfFile:path];
                
                //加保护
                if (dic != nil) {
                    block(dic);
                } else if (arr != nil) {
                    block(arr);
                }
            }

        }
    }
}

//获取路径
+ (NSString *)getPathWithURL:(NSString *)url
{
    //1. 获取cache文件夹路径
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    //2 .MD5加密 转化网址成一串数字
    NSString *urlFile = [CustomerNetworking cachedFileNameForKey:url];
    
    //3. 拼接
    cachePath = [cachePath stringByAppendingPathComponent:urlFile];
    
    return cachePath;
}

//获取路径
+ (NSString *)cachedFileNameForKey:(NSString *)key
{
    const char *str = [key UTF8String];
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    return filename;
}

//判断当前有无网络
+ (NSInteger)getNetWorkStatus
{
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    
    return reach.currentReachabilityStatus;
}


+ (void)removeCache
{
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    for (NSString *p in files) {
        NSString *path = [NSString stringWithFormat:@"%@/%@", cachePath, p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        }
    }
    
    
}
// 计算清除的缓存大小
+ (CGFloat)floatWithPath:(NSString *)path
{
    CGFloat num = 0;
    NSFileManager *man = [NSFileManager defaultManager];
    if ([man fileExistsAtPath:path]) {
        NSEnumerator *childFile = [[man subpathsAtPath:path] objectEnumerator];
        NSString *fileName;
        while ((fileName = [childFile nextObject]) != nil) {
            NSString *fileSub = [path stringByAppendingPathComponent:fileName];
            num += [self fileSizeAtPath:fileSub];
        }
    }
    return num / (1024.0 * 1024.0);
    
}

//计算单个文件大小
+ (long long)fileSizeAtPath:(NSString *)file
{
    NSFileManager *man = [NSFileManager defaultManager];
    if ([man fileExistsAtPath:file]) {
        return [[man attributesOfItemAtPath:file error:nil] fileSize];
    }
    return 0;
}


@end
